package com.ley.springboot.commons.http.filter;

import java.io.IOException;
import java.util.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * request info filter
 **/
@Slf4j
public class RequestInfoFilter implements Filter {

    /**
     * ignore list
     **/
    private static List<String> ignoreList;

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
        ignoreList = Arrays.asList("js", "css", "png", "ico", "gif", "jpg");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        try {
            long startTime = System.currentTimeMillis();
            String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
            if (!isIgnore(uri)) {
                log.info("==================== RequestInfoFilter Start ====================");
                log.info(request.getMethod() + " : " + uri);
                log.info("session存活时间：" + request.getSession().getMaxInactiveInterval());
                this.logHeaders(request);
                this.logParams(request);
                chain.doFilter(request, response);
                long endTime = System.currentTimeMillis();
                log.info(request.getMethod() + " " + "耗时：" + (endTime - startTime) + " ms");
                log.info("==================== RequestInfoFilter End ====================");
            } else {
                chain.doFilter(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void logHeaders(HttpServletRequest request) {
        HashMap headerMap = new HashMap();
        Enumeration<String> headers = request.getHeaderNames();

        while (headers.hasMoreElements()) {
            String headName = headers.nextElement();
            if (headName != null && !"".equals(headName)) {
                headerMap.put(headName, request.getHeader(headName));
            }
        }
        headerMap.put("RemoteHost", request.getRemoteHost() + ":" + request.getRemotePort());
        log.info("headerMap: {}", headerMap);
    }


    private void logParams(HttpServletRequest request) {
        HashMap maps = new HashMap();
        Enumeration keys = request.getParameterNames();

        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            if (StringUtils.isNotEmpty(key)) {
                String values = request.getParameter(key);
                maps.put(key, values);
            }
        }

        log.info(maps.toString());
    }


    private void logAttr(HttpServletRequest request) {
        HashMap attributeMap = new HashMap();
        Enumeration<String> keys = request.getAttributeNames();

        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if (StringUtils.isNotEmpty(key)) {
                Object values = request.getAttribute(key);
                attributeMap.put(key, values);
            }
        }
        log.info("attributeMap: {}", attributeMap.toString());
    }


    private static final boolean isIgnore(String url) {
        boolean ignore = false;
        int index = url.lastIndexOf(".");
        if (index > 0) {
            String subIgnore = url.substring(index + 1, url.length());
            if (ignoreList.contains(subIgnore)) {
                ignore = true;
            }
        }
        return ignore;
    }
}